package com.wzl.consumer.controller.rabbitMqController.basicsConsumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;import com.wzl.common.pojo.VkSmbmsUser;
import com.wzl.consumer.config.rabbitConfig.RabbitConfig;
import com.wzl.consumer.service.rabbitMqService.basicsConsumer.MqBasicsConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.nio.charset.StandardCharsets;

/**
 * 基础用法消费者
 *
 * @author weizhongli
 * @since 2022-09-04 17:41
 */
@Slf4j
@Controller
public class MqBasicsConsumerController {

    @Autowired
    private MqBasicsConsumerService mqBasicsConsumerService;
    @RabbitListener(
            bindings = {
                    @QueueBinding(value = @Queue(value = RabbitConfig.QUEUE, durable = "true"),
                            exchange = @Exchange(value = RabbitConfig.EXCHANGE,type = "direct"),
                            key = RabbitConfig.ROUTING_KEY
                    )
            }, containerFactory = "rabbitFactory")
    @RabbitHandler
    public void testConsumer(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        //解析收到的队列内容
        JSONObject jsonMsg = JSONObject.parseObject(msg);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        System.out.println(jsonMsg);
        try {
            VkSmbmsUser user = createUssCrmEntity(jsonMsg);
            System.out.println(user);
            mqBasicsConsumerService.updateUserById(user.getId(),user.getUsername()+"测试");
            //3.手动签收
            channel.basicAck(deliveryTag,true);
        } catch (Exception e) {
            e.printStackTrace();
            //第三个参数: requeue:重回队列  设置为true 消息重回queue  ,broker从新发送消息给消费者
            channel.basicNack(deliveryTag,true,true);
        }
    }

    private VkSmbmsUser createUssCrmEntity(JSONObject jsonMsg) {
        VkSmbmsUser user = new VkSmbmsUser();
        user.setId(Integer.parseInt(jsonMsg.getString("id")));
        user.setUsercode(jsonMsg.getString("usercode"));
        user.setUsername(jsonMsg.getString("username"));
        user.setUserpassword(jsonMsg.getString("userpassword"));
        user.setGender(Integer.parseInt(jsonMsg.getString("gender")));
        user.setBirthday(jsonMsg.getString("birthday"));
        user.setPhone(jsonMsg.getString("phone"));
        user.setAddress(jsonMsg.getString("address"));
        user.setUserrole(Integer.parseInt(jsonMsg.getString("userrole")));
        return user;
    }

}